package com.xbenben.project.common.init;

import com.xbenben.project.wxpush.entity.ConfigRuleDO;
import com.xbenben.project.wxpush.mapper.ConfigRuleDAO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

/**
 * @author xbenbenx
 * Date:2022/11/21 23:27
 **/
@Component
@Slf4j
public class ConfigRule implements InitData {

    private static Map<String, ConfigRuleDO> mapping = new ConcurrentHashMap<>();
    @Autowired
    private ConfigRuleDAO configRuleDAO;

    /**
     * 获取 实体
     */
    private static ConfigRuleDO getConfigRuleDO(String ruleCode) {
        if (StringUtils.isBlank(ruleCode)) {
            return null;
        }
        return mapping.get(ruleCode);

    }

    /**
     * 初始化 配置
     */
    @Override
    public void loadData() {
        log.info("初始化 配置属性");
        List<ConfigRuleDO> configRuleDOs = configRuleDAO.selectByConfigRuleDO(null);
        if (CollectionUtils.isEmpty(configRuleDOs)) {
            return;
        }
        ConcurrentMap<String, ConfigRuleDO> ruleDOTemp = configRuleDOs.stream().filter(res -> StringUtils.isNotBlank(res.getRuleDef()))
                .collect(Collectors.toConcurrentMap(ConfigRuleDO::getRuleCode, res -> res, (o1, o2) -> o2));
        mapping = ruleDOTemp;
    }
}
